const loginA = document.querySelector(".login-a");
const registerA = document.querySelector(".register-a");


const login = document.querySelector(".login");
const register = document.querySelector(".register");

const registersubmit = document.querySelector(".register form");
const loginsubmit = document.querySelector(".login form");


// 注册
loginA.addEventListener("click", function () {
    login.style.display = "none";
    register.style.display = "block";
});


// 登录
registerA.addEventListener("click", function () {
    register.style.display = "none";
    login.style.display = "block";
});



// 提交事件
// 注册
registersubmit.addEventListener("submit", async function (e) {
    e.preventDefault();
    const username = registersubmit.querySelector("input[name=username]").value.trim();
    const password = registersubmit.querySelector("input[name=password]").value.trim();
    if (username === '' || password === '') {
        // modalshow()
        alert("账号或密码不能为空！");
        return
    }
    if (username.length < 2) {
        alert("账号不能少于二位数");
        return
    } else if (password.length < 6) {
        alert("账号不能少于六位数");
        return
    }

    const res = await axios({
        url: '/api/register',
        method: 'post',
        data: {
            username,
            password
        }
    });
    alert(res.data.message + "点击确认3秒后自动跳转到登录页面");
    setTimeout(() => {
        loginsubmit.querySelector("input[name=username]").value = username
        registerA.click();
    }, 3000);
})

loginsubmit.addEventListener("submit", async function (e) {
    e.preventDefault();
    const username = loginsubmit.querySelector("input[name=username]").value.trim();
    const password = loginsubmit.querySelector("input[name=password]").value.trim();
    if (username === '' || password === '') {
        // modalshow()
        alert("账号或密码不能为空！");
        return
    }
    if (username.length < 2) {
        alert("账号不能少于二位数");
        return
    } else if (password.length < 6) {
        alert("账号不能少于六位数");
        return
    }

    const res = await axios({
        url: '/api/login',
        method: 'post',
        data: {
            username,
            password
        }
    });
    console.log(res);
    console.log(res.data.token);

    alert("点击确认三秒后跳转到首页");
    localStorage.setItem("token", res.data.token);

    setTimeout(() => {
        location.href = "index.html"
    }, 3000);
})



